package se.wangs.proxydemo;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * -- coding: UTF-8 -- *
 *
 * @author wangs
 * @date 2023/12/13 14:30
 * @description 代理方法，动态代理
 */
public class EatProxy implements InvocationHandler {
    // 动态代理对象是不确定的，在运行的时候才能确定，因此，我们这里可以指定一个Object类型
    private Object target;

    public EatProxy(Object target) {
        this.target = target;
    }

    /**
     *
     * @param proxy the proxy instance that the method was invoked on
     *
     * @param method the {@code Method} instance corresponding to
     * the interface method invoked on the proxy instance.  The declaring
     * class of the {@code Method} object will be the interface that
     * the method was declared in, which may be a superinterface of the
     * proxy interface that the proxy class inherits the method through.
     *
     * @param args an array of objects containing the values of the
     * arguments passed in the method invocation on the proxy instance,
     * or {@code null} if interface method takes no arguments.
     * Arguments of primitive types are wrapped in instances of the
     * appropriate primitive wrapper class, such as
     * {@code java.lang.Integer} or {@code java.lang.Boolean}.
     *
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("开始做饭...");
        System.out.println("饭做好了...");
        /*
        * 这里的method就是代理对象中的核心方法
        * method.invoke()
        *   参数1：代理对象的实例
        *   参数2：该方法的参数
        * */
        Object invoked = method.invoke(target, args);
        System.out.println("洗碗...");
        return invoked;
    }
}
